<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    :okButtonProps="{ class: { 'jee-hidden': disableSubmit } }"
    @cancel="close"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :rules="validatorRules" :model="form" v-bind="formItemLayout">
        <a-form-model-item label="姓名" prop="realname">
          <a-input placeholder="请输入姓名" v-model="form.realname" :disabled="disableSubmit" />
        </a-form-model-item>
        <a-form-model-item label="账号" prop="username">
          <a-tooltip :trigger="['hover']" placement="topLeft">
            <template slot="title" v-if="userId"> 账号不能编辑 </template>
            <a-input placeholder="请输入账号" v-model="form.username" :disabled="disableSubmit" :readOnly="!!userId" />
          </a-tooltip>
        </a-form-model-item>
        <template v-if="!userId">
          <a-form-model-item label="登录密码" prop="password">
            <a-input type="password" placeholder="请输入登录密码" v-model="form.password" />
          </a-form-model-item>
          <a-form-model-item label="确认密码" prop="confirmpassword">
            <a-input
              type="password"
              @blur="handleConfirmBlur"
              placeholder="请重新输入登录密码"
              v-model="form.confirmpassword"
            />
          </a-form-model-item>
        </template>
        <a-form-model-item label="网格" prop="selectedDeparts">
          <a-tree-select
            style="width: 100%"
            v-model="form.selectedDeparts"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择网格"
            allow-clear
            tree-default-expand-all
            :treeData="treeDatas"
            :disabled="disableSubmit"
          />
        </a-form-model-item>
        <a-form-model-item label="角色" prop="selectedRoles">
          <j-multi-select-tag
            :disabled="disableSubmit"
            v-model="form.selectedRoles"
            :options="rolesOptions"
            placeholder="请选择角色"
          />
        </a-form-model-item>
        <a-form-model-item label="联系方式" prop="phone">
          <a-input placeholder="请输入手机号码" :disabled="disableSubmit" v-model="form.phone" />
        </a-form-model-item>
        <a-form-model-item label="公民身份号码" prop="identityNumber">
          <a-input v-model="form.identityNumber" :disabled="disableSubmit" placeholder="请输入公民身份号码" />
        </a-form-model-item>
        <a-form-model-item label="出生日期" prop="birthday">
          <a-date-picker
            style="width: 100%"
            placeholder="请选择出生日期"
            v-model="form.birthday"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            :disabled="disableSubmit"
            :getCalendarContainer="node => node.parentNode"
          />
        </a-form-model-item>
        <a-form-model-item label="性别" prop="sex">
          <a-radio-group v-model="form.sex" :disabled="disableSubmit" placeholder="请选择性别">
            <a-radio :value="1"> 男 </a-radio>
            <a-radio :value="2"> 女 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="政治面貌">
          <a-input v-model="form.politicalFace" :disabled="disableSubmit" placeholder="请输入政治面貌" />
        </a-form-model-item>
        <a-form-model-item label="学历">
          <a-select v-model="form.degree" :options="degreeOptions" :disabled="disableSubmit" placeholder="请选择"/>
        </a-form-model-item>
        <a-form-model-item label="上传照片">
          <j-image-upload class="avatar-uploader" text="上传" v-model="form.avatar" :disabled="disableSubmit" />
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </j-modal>
</template>

<script>
import * as structureApi from '@/api/xlgc/structure.js'
import { duplicateCheck, queryall, queryUserRole } from '@/api/api'
export default {
  name: 'EditModal',
  props: {
    title: {
      type: String,
      default: ''
    },
    treeDatas: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 }
      },
      visible: false,
      disableSubmit: false,
      form: {},
      confirmLoading: false,
      confirmDirty: false,
      userId: null,
      rolesOptions: [],
      politicalFaceOptions: [
        { title: '中共党员', key: '01' },
        { title: '中共预备党员', key: '02' },
        { title: '共青团员', key: '03' },
        { title: '民革党员', key: '04' },
        { title: '民盟盟员', key: '05' },
        { title: '民建会员', key: '06' },
        { title: '民进会员', key: '07' },
        { title: '农工党党员', key: '08' },
        { title: '致公党党员', key: '09' },
        { title: '九三学社社员', key: '10' },
        { title: '台盟盟员', key: '11' },
        { title: '无党派人士', key: '12' },
        { title: '群众（现称普通居民，与居民身份证相对应', key: '13' }
      ],
      degreeOptions: [
        { title: '高中', key: 1 },
        { title: '大专', key: 2 },
        { title: '本科', key: 3 },
        { title: '研究生', key: 4 },
        { title: '博士', key: 5 },
        { title: '博士后', key: 6 },
        { title: '其他', key: 0 }
      ],
      validatorRules: {
        username: [
          { required: true, message: '请输入账号!' }, { validator: this.validateUsername },
          { pattern: /^[a-zA-Z0-9_]{0,}$/, message: '账号不能包有中文或者特殊字符' }
        ],
        password: [
          {
            required: true,
            pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
            message: '密码由8位数字、大小写字母和特殊符号组成!'
          },
          { validator: this.validateToNextPassword, trigger: 'change' }
        ],
        confirmpassword: [
          { required: true, message: '请重新输入登录密码!' },
          { validator: this.compareToFirstPassword }
        ],
        realname: [{ required: true, message: '请输入姓名!' }],
        selectedDeparts: [{ required: true, message: '请选择网格' }],
        selectedRoles: [{ required: true, message: '请选择角色' }],
        phone: [{ required: true, message: '请输入手机号!' }, { validator: this.validatePhone }],
        identityNumber: [{ required: true, message: '请输入公民身份号码' }, { validator: this.idCardValidata }],
        birthday: [{ required: true, message: '请选择出生日期' }],
        sex: [{ required: true, message: '请选择性别' }],
        roles: {}
      }
    }
  },
  computed: {},
  created () {
    this.initRoleList()
  },
  methods: {
    add() {
      this.visible = true
      this.$nextTick(() => {})
    },
    edit(record) {
      this.userId = record.id
      this.visible = true
      this.getUserWGY()
      if (this.userId) {
        this.getUserRoles(this.userId)
      }
      this.$nextTick(() => {})
    },
    close() {
      this.$emit('close')
      this.visible = false
      setTimeout(() => {
        this.disableSubmit = false
        this.userId = null
        this.form = {}
      }, 500)
    },
    // 查看网格员信息
    getUserWGY() {
      this.confirmLoading = true
      structureApi.userWGY(this.userId).then(res => {
        this.confirmLoading = false
        if (res.success) {
          this.form = Object.assign({}, this.form, res.result)
          let departs = this.form && this.form.departs ? this.form.departs.map(v => v.departId) : []
          this.$set(this.form, 'id', this.userId)
          this.$set(this.form, 'selectedDeparts', departs.join(','))
        } else {
          this.$message.warn(res.message)
        }
      }).catch(e => {
        this.confirmLoading = false
        this.$message.warn('请求失败！')
      })
    },
    // 提交确定
    handleOk() {
      this.$refs.form.validate(valid => {
        if (valid) {
          let api = this.userId ? structureApi.updateWGY(this.form) : structureApi.addWGY(this.form)
          api.then(res => {
            if (res.success) {
              this.$message.success(res.message ? res.message : '操作成功')
              this.$emit('ok')
              this.close()
            } else {
              this.$message.warn(res.message ? res.message : '操作失败')
            }
          })
          .catch(e => {
            this.$message.warn('请求失败！')
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 初始化角色字典
    initRoleList() {
      queryall().then((res) => {
        if (res.success) {
          this.rolesOptions = res.result.map((item, index, arr) => {
            let c = { label: item.roleName, value: item.id }
            return c
          })
          console.log('this.rolesOptions: ', this.rolesOptions)
        }
      })
    },
    // 获取当前用户得所有角色
    getUserRoles(userid) {
      queryUserRole({ userid: userid }).then((res) => {
        if (res.success) {
          let result = res.result.join(',')
          this.$set(this.form, 'selectedRoles', result)
        }
      })
    },
    validateUsername(rule, value, callback) {
      var params = {
        tableName: 'sys_user',
        fieldName: 'username',
        fieldVal: value,
        dataId: this.userId
      }
      duplicateCheck(params).then(res => {
        if (res.success) {
          callback()
        } else {
          callback('账号已存在!')
        }
      })
    },
    compareToFirstPassword(rule, value, callback) {
      if (value && value !== this.form.password) {
        callback('两次输入的密码不一样！')
      } else {
        callback()
      }
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        callback()
      } else {
        if (new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)) {
          var params = {
            tableName: 'sys_user',
            fieldName: 'phone',
            fieldVal: value,
            dataId: this.userId
          }
          duplicateCheck(params).then(res => {
            if (res.success) {
              callback()
            } else {
              callback('手机号已存在!')
            }
          })
        } else {
          callback('请输入正确格式的手机号码!')
        }
      }
    },
    idCardValidata(rule, value, callback) {
      // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
      let reg = new RegExp(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/)
      if (value && !reg.test(value)) {
        callback('当前身份证不符合规范!')
      } else {
        callback()
      }
    },
    handleConfirmBlur(e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
    }
  }
}
</script>
<style lang="less" scoped></style>
